package com.lovemanai.dao;

import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.handlers.BeanListHandler;

import com.lovemanai.tools.jdbc.JdbcUtils;
import com.lovemanai.tools.jdbc.TxQueryRunner;

/**
 * 数据库操作类
 * @author lovemanai
 *
 */
public class DbDao {
	
	private TxQueryRunner tx = null;
	
	
	
	public DbDao() {
		 tx = new TxQueryRunner();
	}

	/**
	 * 执行查询语句
	 * @param sql
	 * @param clazz
	 * @param params
	 * @return
	 */
	public <T> List<T> query(String sql, Class<T> clazz, Object... params) {
		
		try {
			List<T> listObject = (List<T>) tx.query(sql, params, new BeanListHandler<T>(clazz));
			return listObject;
		} catch (Exception e) {
			throw new RuntimeException(e); 
		}
	}
	
	/**
	 * 执行增删改语句
	 * @param sql
	 * @param params
	 * @return
	 */
	public int update(String sql, Object... params) {
		int result = 0;
		try {
			JdbcUtils.beginTransaction();// 开启事务
			result = tx.update(sql, params);
			JdbcUtils.commitTransaction();//提交事务
			return result;
		} catch (SQLException e) {
			try {
				JdbcUtils.rollbackTransaction();//出现Exception回滚事务
			} catch (SQLException e1) {
				e1.printStackTrace();
			}
			e.printStackTrace();
		}
		return result;
	}
	
}
